<?php
namespace app\index\controller;
use app\common\model\Order;
use app\common\traits\SendMessage;
use think\Controller;
use think\Db;
use think\helper\Time;
use think\Request;
class Index extends Controller
{
    use SendMessage;

    public function index()
    {
        $this->redirect('admin/index/index');
    }

    //拍摄前一天晚上18:30自动批量发送 (注：已停发)
//    public function psAutoSendmsg(){
//        $order = new Order();
//        $tomorrow = [mktime(0, 0, 0, date('m'), date('d')+1, date('Y')), mktime(23, 59, 59, date('m'), date('d')+1, date('Y'))];
//        $time = date('Y-m-d H:i:s',time());
//        //预约成功
//        $orderinfos = $order->where(['yypstime'=>['between',$tomorrow],'psautomsgflag'=>['in',[1,2]],'ywstate'=>5,'status'=>1])->field('id,maphone,ywstate,yykf,yycg,yypstime,automsgflag,hsautomsgflag')->limit(100)->select();
//        foreach ($orderinfos as $data){
//            $msgdata = $this->auto_psMsgData($data);
//            $result = $this->sendSmss($msgdata);
//            if($result){
//                Db::name('order')->where(['id'=>$data['id']])->setField('psautomsgflag',3);
//                $log = $this->getLogData($data);
//                $log['psautomsgflag'] = 3;
//                $log['operation'] = 11;
//                $log['ywstate'] = $data['ywstate'];
//                $log['yykf'] = $data['yykf'];
//                $log['yycg'] = $data['yycg'];
//                $log['automsgflag'] = $data['automsgflag'];
//                $log['hsautomsgflag'] = $data['hsautomsgflag'];
//                Db::name('order_log')->insert($log);
//                echo "{$time}发送成功<br/>";
//            }else{
//                echo "{$time}发送失败<br/>";
//            }
//        }
//    }
//
//    public function auto_psMsgData($data){
//        $msgdata['phone'] = $data['maphone'];
//        $msgdata['orderid'] = $data['id'];
//        $yycginfo = Db::name('group')->where(['id' => $data['yycg'], 'status' => 1])->find();
//        $yaoyueInfo = getYykfInfo($data['yykf']);
//        $msgdata['param'] = [
//            'yykf'   =>$yaoyueInfo['username'],
//            'addr'   => $yycginfo['address'],
//            'phone'  => $yaoyueInfo['phone'],
//            'time' => changeTime($data['yypstime']),
//            'tel' => $yycginfo['tel']
//        ];
//        $msgdata['tempcode'] = 'SMS_75925003';
//        return $msgdata;
//    }


    //预约课程自动批量发送
//    public function hsAutoSendmsg(){
//        $order = new Order();
//        $tomorrow = [mktime(0, 0, 0, date('m'), date('d')+1, date('Y')), mktime(23, 59, 59, date('m'), date('d')+1, date('Y'))];
//        $time = date('Y-m-d H:i:s',time());
//        $orderinfos = $order->where(['yysktime'=>['between',$tomorrow],'hsautomsgflag'=>2,'hdstate'=>76,'status'=>1])->field('id,maphone,hdstate,hsdzid,yysktime,kcid,yyhdnum,automsgflag,psautomsgflag')->limit(100)->select();
//        foreach ($orderinfos as $data){
//            $msgdata = $order->hsMsgData($data);
//            $result = $this->sendSmss($msgdata);
//            if($result){
//                Db::name('order')->where(['id'=>$data['id']])->setField('hsautomsgflag',3);
//                $log = $this->getLogData($data);
//                $log['hsautomsgflag'] = 3;
//                $log['operation'] = 12;
//                $log['hdstate'] = $data['hdstate'];
//                $log['hsmd'] = $data['hsdzid'];
//                $log['hsdzid'] = $data['hsdzid'];
//                $log['kcid'] = $data['kcid'];
//                $log['automsgflag'] = $data['automsgflag'];
//                $log['psautomsgflag'] = $data['psautomsgflag'];
//                Db::name('order_log')->insert($log);
//                echo "{$time}发送成功<br/>";
//            }else{
//                echo "{$time}发送失败<br/>";
//            }
//        }
//    }

    //推广短信（宝宝成长册短信）
//    public function TgSendmsg(){
//        $orderinfos = Db::name('order')->where(['yctime'=>['gt',1504195200],'tgsendmsg'=>1])->field('id,maphone,tgsendmsg')->limit(200)->select();
////        $orderinfos = Db::name('order')->where(['yctime'=>['gt',1504195200],'tgsendmsg'=>1])->field('id,maphone,tgsendmsg')->count();
//        foreach ($orderinfos as $data){
//            $msgdata['phone'] = $data['maphone'];
//            $msgdata['orderid'] = $data['id'];
//            $msgdata['tempcode'] = 'SMS_77220020'; //推广短信
//            $msgdata['freesignname'] = '玛瑞莎';
//            $result = $this->sendSmss($msgdata);
////            $result = true;
//            if($result){
//                Db::name('order')->where(['id'=>$data['id']])->setField('tgsendmsg',2);
//                $log = $this->getLogData($data);
//                $log['operation'] = 17;
//                Db::name('order_log')->insert($log);
//                echo "{$time}发送成功<br/>";
//            }else{
//                echo "{$time}发送失败<br/>";
//            }
//        }
//    }

    //温馨提示
//    public function WxtsSendmsg(){
//        $orderinfos = Db::name('order')->where(['yctime'=>['gt',1504195200],'wxtssendmsg'=>1,'ywstate'=>['neq',6]])->field('id,maphone,wxtssendmsg')->limit(200)->select();
//        foreach ($orderinfos as $data){
//            $msgdata['phone'] = $data['maphone'];
//            $msgdata['orderid'] = $data['id'];
//            $msgdata['tempcode'] = 'SMS_79110063'; //推广短信
//            $msgdata['freesignname'] = '玛瑞莎';
//            $result = $this->sendSmss($msgdata);
//            if($result){
//                Db::name('order')->where(['id'=>$data['id']])->setField('wxtssendmsg',2);
//                $log = $this->getLogData($data);
//                $log['operation'] = 19;
//                Db::name('order_log')->insert($log);
//                echo "{$time}发送成功<br/>";
//            }else{
//                echo "{$time}发送失败<br/>";
//            }
//        }
//    }

    public function syAutoStatus(){
        $url = 'http://222.180.151.118:8086/Introduce.asmx/introduceMain';
//        $sql = "SELECT id,maphone FROM jtds_order  WHERE ywstate = 5 AND jinpaipp = 1 AND status = 1 AND yypstime <> NOW() AND  id IN (SELECT id FROM jtds_order a INNER JOIN jtds_jinpaiorder b ON a.maphone <> b.CusMomPhone) LIMIT 10";
//        $info =  Db::query($sql);
        $info = Db::name('order')->field(['id','maphone'])->where(['ywstate'=>['eq',5],'jinpaipp'=>['eq',1],'status'=>['eq',1],'yypstime'=>['elt',time()]])->limit(10)->select();
        foreach ($info as $k=>$v){
            $jsonStr['keyword'] = "MRS";
            $jsonStr['phone'] = $v['maphone'];
            //$jsonStr  = json_encode($jsonStr);
            $data= self::http_post_json($url,$jsonStr);
            $data = json_decode($data,true);
            $data = json_decode($data['d'],true);
            if(!empty($data[0]['PodNo'])){
                $arr[$k]  = $data;
                $data[0]['shootDate'] = strtotime($data[0]['shootDate']);
                $data[0]['order_id'] = $v['id'];
                Db::name('order')->where(['id'=>$v['id']])->setField('jinpaipp',2);
                $res = null;
                $res =  Db::name('jinpaiorder')->where(['CusMomPhone'=>$v['maphone']])->find();
                if(empty($res)) {
                    Db::name('jinpaiorder')->insert($data[0]);
                }
            }else{
                Db::name('order')->where(['id'=>$v['id']])->setField('jinpaipp',3);
            }
        }
        echo "执行成功/n";
    }
    public function Pipeixx(){
        $timepp = strtotime("-3 day");
        self::PipeiAutoStatus($id=3,$jinpaipp=4,$jinpaipp=5,$timepp);
    }
    //匹配接口
    public static function PipeiAutoStatus($id=1,$jinpaipp=2,$jinpaix=3,$timepp){
        $url = 'http://222.180.151.118:8086/Introduce.asmx/introduceMain';
        $info = Db::name('order')->field(['id','maphone'])->where(['ywstate'=>['eq',5],'jinpaipp'=>['eq',$id],'status'=>['eq',1],'yypstime'=>['elt',$timepp]])->limit(10)->fetchSql(false)->select();
        foreach ($info as $k=>$v){
            $jsonStr['keyword'] = "MRS";
            $jsonStr['phone'] = $v['maphone'];
            //$jsonStr  = json_encode($jsonStr);
            $data= self::http_post_json($url,$jsonStr);
            $data = json_decode($data,true);
            $data = json_decode($data['d'],true);
            if(!empty($data[0]['PodNo'])){
                $arr[$k]  = $data;
                $data[0]['shootDate'] = strtotime($data[0]['shootDate']);
                $data[0]['order_id'] = $v['id'];
                Db::name('order')->where(['id'=>$v['id']])->setField('jinpaipp',$jinpaipp);
                $res = null;
                $res =  Db::name('jinpaiorder')->where(['CusMomPhone'=>$v['maphone']])->find();
                if(empty($res)) {
                    Db::name('jinpaiorder')->insert($data[0]);
                }
            }else{
                Db::name('order')->where(['id'=>$v['id']])->setField('jinpaipp',$jinpaix);
            }
        }
        echo "执行成功/n";
    }
    //请求接口
    public  static  function http_post_json($url, $jsonStr)
    {
        $data_string = json_encode($jsonStr);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string))
        );
        $result = curl_exec($ch);
        return $result;
    }
    //修改数据
    public function gsAutoStatus(){
        $info  = Db::name('jinpaiorder')->where('status',0)->limit(50)->select();
        $ip = $_SERVER["REMOTE_ADDR"];
        foreach ($info as $k=>$v){
           $data = '金牌订单编号:'.$v['PodNo'].'，顾客姓名：'.$v['CusMomName'].'，妈妈电话：'.$v['CusMomPhone'].'，拍摄时间：'.date('Y-m-d H:i',$v['shootDate']).'，拍摄门店：'.$v['DepName'];
           $res = Db::name('order')->where(['id'=>$v['order_id'],'ywstate'=>5])->update(['cgpstime'=>time(),'ywstate'=>6,'jinpaibz'=>$data]);
           if($res){
               $list[$k] =  Db::name('order_log')->fetchSql(false)->insert(['order_id'=>$v['order_id'],'khd'=>3,'jinpaibz'=>$data,'operation'=>9,'maphone'=>$v['CusMomPhone'],'ywstate'=>6,'ip'=>$ip]);
               Db::name('jinpaiorder')->where('ids',$v['ids'])->setField('status',1);
           }
        }
        echo "更新成功/n";
    }


    //分配专员后早9晚6定时发短信给顾客
    public function fpzyAutoMsg(){
        $yesterday = time() - 72000;//倒退20个小时的时间
        $orders = Db::name('order')->field(['id','maphone','yykf','ywstate','psautomsgflag','hsautomsgflag'])->where(['automsgflag'=>2,'automsgtime'=>['between',[$yesterday,time()]],'ywstate'=>['in',[1,2,4,5,7,9]]])->select();
        foreach ($orders as $info){
            $msgdata['phone'] = $info['maphone'];
            $msgdata['orderid'] = $info['id'];
            $userinfo = DB::name('users')->where(['depar_id' => 3, 'id' => $info['yykf'], 'status' => 1])->find();
            $msgdata['param'] = [
                'pai' => '爱心送',
                'num' =>'2套及妆面造型（准爸爸可入镜）赠底片、精放、相卡各6张，以上内容无任何隐形消费或附加费',
                'addr'=>'春熙路、晋阳路、驷马桥',
                'telyykf' =>'/微信:'.$userinfo['phone'].$userinfo['username'],
            ];
            $msgdata['tempcode'] = 'SMS_105045089';
            $result = $this->sendSmss($msgdata);
            if($result){
                Db::name('order')->where(['id'=>$info['id']])->setField('automsgflag',3);
                $log = $this->getLogData($info);
                $log['automsgflag'] = 3;
                $log['operation'] = 10;
                $log['ywstate'] = $info['ywstate'];
                $log['yykf'] = $info['yykf'];
                $log['hsautomsgflag'] = $info['hsautomsgflag'];
                $log['psautomsgflag'] = $info['psautomsgflag'];
                Db::name('order_log')->insert($log);
                echo "发送成功/n";
            }else{
                echo "发送失败/n";
            }
        }
    }

    public function getLogData($data){
        $log['order_id'] = $data['id'];
        $log['maphone'] = $data['maphone'];
        $log['khd'] = 3;
        $log['ip'] = request()->ip();
        $log['cztime'] = time();
        return $log;
    }

//    //准备改的分配专员发短信
//    public function fpzyAutoMsg_one(){
//        $orders = Db::name('order')->field(['id','maphone','yykf','ywstate'])->where(['automsgflag'=>2,'automsgtime'=>['elt',time()]])->limit(100)->select();
//        foreach ($orders as $info){
//            $msgdata = getFpzyMsgCommonData($info);
//            $msgdata['tempcode'] = 'SMS_68410086';
//            $result = $this->sendSmss($msgdata);
//            if($result){
//                Db::name('order')->where(['id'=>$info['id']])->setField('automsgflag',3);
//                FpzyMsgAddLog($info,3);
//                echo "发送成功/n";
//            }else{
//                echo "发送失败/n";
//            }
//        }
//    }


    //分配专员一个月后系统自动发短信
    public function fpzy_FirstMonth_AutoMsg(){
        $oneMonthAgoTime = mktime(23, 59, 59, date('m')-1, date('d'), date('Y'));//前一个月的日期的结束值
        $orders = Db::name('order')->field(['id','maphone','yykf','ywstate'])->where(['automsgflag'=>3, 'yyfptime'=>['elt',$oneMonthAgoTime], 'ywstate'=>['not in',[3,5,6]] ,'status'=>1])->limit(100)->select();
        foreach ($orders as $info){
            $msgdata = getFpzyMsgCommonData($info);
            $msgdata['tempcode'] = 'SMS_74755037';
            $result = $this->sendSmss($msgdata);
            if($result){
                Db::name('order')->where(['id'=>$info['id']])->setField('automsgflag',4);
                FpzyMsgAddLog($info,4,13);//记录日志
            }
        }
        echo "发送成功/n";
    }


    //分配专员三个月后系统自动发短信
    public function fpzy_ThirdMonth_AutoMsg(){
        $thirdMonthAgoTime = mktime(23, 59, 59, date('m')-3, date('d'), date('Y'));//前三个月的时间结束值
        $orders = Db::name('order')->field(['id','maphone','yykf','ywstate'])->where(['automsgflag'=>4, 'yyfptime'=>['elt',$thirdMonthAgoTime] ,'ywstate'=>['not in',[3,5,6]],'status'=>1])->limit(100)->select();
        foreach ($orders as $info){
            $msgdata = getFpzyMsgCommonData($info);
            $msgdata['tempcode'] = 'SMS_75630001';
            $result = $this->sendSmss($msgdata);
            if($result){
                Db::name('order')->where(['id'=>$info['id']])->setField('automsgflag',5);
                FpzyMsgAddLog($info,5,14);//记录日志
            }
        }
        echo "发送成功/n";
    }

    //渠道:批量导入订单系统自动发短信
//    public function qddaoru_Auto_sendMsg(){
//        $orders = Db::name('order')->field(['id','maphone','ywstate'])->where(['qddrmsgflag'=>2, 'daoru'=>2 ,'qd_depar'=>1,'ywstate'=>4,'status'=>1 ])->limit(100)->select();
//        foreach($orders as $info){
//            $msgdata['orderid'] = $info['id'];
//            $msgdata['phone'] = $info['maphone'];
//            $msgdata['param'] = ['phone' => '61611953'];
//            $msgdata['tempcode'] = 'SMS_74795036';
//            $result = $this->sendSmss($msgdata);
//            if($result){
//                Db::name('order')->where(['id'=>$info['id']])->setField('qddrmsgflag',3);
//                $log = $this->getLogData($info);
//                $log['operation'] = 15;
//                Db::name('order_log')->insert($log);
//            }
//        }
//        echo "发送成功/n";
//    }

    //预约成功或修改拍摄时间一个月后系统自动发提示短信
    public function yycg_oneMonth_autoMsg(){
        $orders = Db::name('order')->where(['yyoneyuetsmsgtime'=>['between',Time::today()],'yyoneyuetsmsgflag'=>1,'ywstate'=>5])->select();

        foreach ($orders as $info){
            $msgdata = [];
            if($info['qd_depar'] == 2){
                $yykf = Db::name('users')->where(['id'=>$info['jdry']])->find();
            }else{
                $yykf = getYykfInfo($info['yykf']);
            }
            $yycg = Db::name('group')->field('title')->where('id',$info['yycg'])->find();
            $msgdata['orderid'] = $info['id'];
            $msgdata['phone'] = $info['maphone'];
            $msgdata['param'] = ['yykf' => $yykf['username'],'timeyycg'=>date('n月j日',$info['yypstime']).$yycg['title']];
            $msgdata['tempcode'] = 'SMS_105190065';
            $result = $this->sendSmss($msgdata);
            if($result){
                Db::name('order')->where(['id'=>$info['id']])->setField('yyoneyuetsmsgflag',2);
                $log = $this->getLogData($info);
                $log['operation'] = 20;
                Db::name('order_log')->insert($log);
            }
        }
        echo "发送成功/n";
    }




}
